package com.czmini.cztest.util;

import com.alibaba.fastjson.JSONObject;
import com.czmini.cztest.constants.UserConstants;
import com.czmini.cztest.dto.jenkins.RequestInfoDto;
import com.czmini.cztest.entity.ZcTestTask;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import com.offbytwo.jenkins.helper.JenkinsVersion;
import com.offbytwo.jenkins.model.Job;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;
import org.testng.annotations.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JenkinsUtil {

    public static void buildJenkins(String[] args)throws  Exception {
        //加载Jenkins的文件
        ClassPathResource classPathResource = new ClassPathResource("jenkinsDir/.xml");
        // 获取文件流
        InputStream inputStream = classPathResource.getInputStream();
        String jobConfigXml=FileUtil.getText(inputStream);

        String baseUrl="http://stuq.ceshiren.com:8080/";
        String userName="hogwarts";
        String passWord="hogwarts123";

        String jobName="testzc2c";

        JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(new URI(baseUrl),userName,passWord);
        String version = jenkinsHttpClient.getJenkinsVersion();
        System.out.println(version);

        JenkinsServer jenkinsServer = new JenkinsServer(jenkinsHttpClient);
      //  jenkinsServer.createJob(jobName,jobConfigXml,true);

        Map<String, Job> jobMap = jenkinsServer.getJobs();
        // 获取job
        Job job = jobMap.get("testzc2c");
        HashMap<String, String> map = new HashMap<>();
        map.put("userId","16");
        map.put("remark","张成的测试平台演示");
        //构建
        job.build(map,true);
        System.out.println("");

     /*   Job job = jobs.get("");
        // 有参构建
        job.build();*/

    }

    // 获取执行测试的job名称
    public static String getStartTestJobName(Integer createUserId) {
        String jobName="_" +createUserId;
        return jobName;
    }

    public static String getJobSignByName(String jobName) {
        if(StringUtils.isEmpty(jobName) || !jobName.contains("_")){
            return "";
        }
        String jobSign= jobName.substring(0,jobName.lastIndexOf("_"));  // 判断下标最后是_
        return jobSign;
    }

    public static StringBuilder getUpdateTaskStatusUrl(RequestInfoDto requestInfoDto, ZcTestTask zcTestTask) {
        StringBuilder updateStatusUrl = new StringBuilder();

        updateStatusUrl.append("curl -X PUT ");
        updateStatusUrl.append("\""+requestInfoDto.getBaseUrl() + "/task/status \" ");
        updateStatusUrl.append("-H \"Content-Type: application/json \" ");
        updateStatusUrl.append("-H \"token: "+requestInfoDto.getToken()+"\" ");
        updateStatusUrl.append("-d ");
        JSONObject json = new JSONObject();

        json.put("taskId",zcTestTask.getId());
        json.put("status", UserConstants.STATUS_THREE);
        json.put("buildUrl","${BUILD_URL}");


        updateStatusUrl.append("\""+json.toJSONString()+"\"");

        return updateStatusUrl;
    }

    /**
     *
     * @param requestInfoDto Jenkins 操作
     * @param zcTestTask 执行任务
     * @return
     */
    public static StringBuilder StringBuilder(RequestInfoDto requestInfoDto, ZcTestTask zcTestTask){
        StringBuilder updateStatusUrl = new StringBuilder();
        updateStatusUrl.append("curl -X PUT ");
        updateStatusUrl.append("\""+requestInfoDto.getBaseUrl()+"/task/status \""); // 获取对应任务的状态
        updateStatusUrl.append(" -H \"Content-Type: application/json\"");
        updateStatusUrl.append(" -H \"token: "+requestInfoDto.getToken()+"\"");
        updateStatusUrl.append("-d ");

        JSONObject jsonObject = new JSONObject();
        // 参数赋值
        jsonObject.put("taskId",zcTestTask.getId());
        jsonObject.put("status", UserConstants.STATUS_THREE);  // 执行完成
        jsonObject.put("buildUrl","${BUILD_URL}");

        updateStatusUrl.append("'"+jsonObject.toJSONString()+"'");

        return updateStatusUrl;

    }



    @Test
    public void test1() throws URISyntaxException {
        String baseUrl="http://stuq.ceshiren.com:8080/";
        URI uri = new URI(baseUrl);
        JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(uri, "hogwarts", "hogwarts123");
        System.out.println("版本"+jenkinsHttpClient.getJenkinsVersion());
    }

   // Jenkinsserver
    @Test
    public void test2() throws URISyntaxException, IOException {
        //加载Jenkins的文件
        ClassPathResource classPathResource = new ClassPathResource("jenkinsDir/zc.xml.bak");
        // 获取文件流
        InputStream inputStream = classPathResource.getInputStream();
        String jobConfigXml=FileUtil.getText(inputStream);

        String baseUrl="http://stuq.ceshiren.com:8080/";
        URI uri = new URI(baseUrl);
        JenkinsHttpClient jenkinsHttpClient = new JenkinsHttpClient(uri, "hogwarts", "hogwarts123");

        JenkinsServer jenkinsServer = new JenkinsServer(jenkinsHttpClient);
        JenkinsVersion version = jenkinsServer.getVersion();
        System.out.println("版本"+version);

        // 创建Job
       // jenkinsServer.createJob("zczc0430",jobConfigXml,true);

        Map<String, Job> jobs = jenkinsServer.getJobs();
        for (String key : jobs.keySet()) {
            System.out.println("job的名称 ："+key);
        }
        // 获取job
       Job job=jobs.get("zczc0430");
        // 赋值参数
        HashMap<String, String> map = new HashMap<>();
        map.put("userId","12");
        map.put("remark","备注");
        map.put("testCommand","pwd");

        // 构建job
        job.build(map,true);
        System.out.println("");

    }

}
